using Microsoft.Win32;

namespace NewProcessGuarder.toolFunc
{
    /// <summary>
    /// 设置开机启动
    /// </summary>
    public class AutoStart
    {
        /// <summary>
        /// 取消开机启动
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static bool EraseAutoRun(string keyName)
        {
            try
            {
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runKey == null)
                {
                    runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                runKey.DeleteValue(keyName);
                runKey.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 写注册表设置开机启动
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool SetAutoRun(string keyName, string filePath)
        {
            try
            {
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runKey == null)
                {
                    runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                runKey.SetValue(keyName, filePath, RegistryValueKind.String);
                runKey.Close();
            }
            catch(System.Exception ex)
            {
                string msg = ex.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查是否开机启动
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static bool IsAutoRun(string keyName)
        {
            try
            {
                bool _exit = false;
                RegistryKey hkml = Registry.LocalMachine;
                RegistryKey runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runKey == null)
                {
                    runKey = hkml.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                string[] subkeyNames;
                subkeyNames = runKey.GetValueNames();
                foreach (string kName in subkeyNames)
                {
                    if (kName == keyName)
                    {
                        _exit = true;
                        return _exit;
                    }
                }
                runKey.Close();
                return _exit;
            }
            catch
            {
                return false;
            }
        }
    }
}
